package com.project.m.api.busi.handlers.hicatcard.card;


import com.project.m.api.busi.bean.hicatcard.card.CardChangeItem;
import com.project.m.api.busi.bean.hicatcard.card.CardChangeListQueryResp;
import com.project.m.api.busi.config.BusiError;
import com.project.m.api.busi.db.entity.hicatcard.card.TCard;
import com.project.m.api.busi.db.service.hicatcard.card.CardService;
import com.project.m.api.busi.handlers.DefaultBizParamChecker;
import com.project.m.api.validates.ValidateParam;
import com.project.m.api.validates.ValidateRet;
import com.project.m.api.validates.ValidateType;
import com.project.m.api.validates.ValidateUtil;
import com.project.m.api.busi.bean.hicatcard.card.CardChangeListQueryReq;
import com.project.m.api.busi.util.TimeUtil;
import com.project.m.api.common.biz.BizHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class CardChangeListQueryBizHandler extends DefaultBizParamChecker<CardChangeListQueryReq, CardChangeListQueryResp>
        implements BizHandler<CardChangeListQueryReq, CardChangeListQueryResp> {

    @Autowired
    CardService cardService;

    @Value("${image.upload.url}")
    private String imageUploadUrl;

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public CardChangeListQueryResp handle(CardChangeListQueryReq bizRequest) throws Exception {
        CardChangeListQueryResp bizResp = new CardChangeListQueryResp();
        // 参数检查
        ValidateRet vRet = checkParam(bizRequest, bizResp);
        if (!vRet.isValid()) {
            return bizResp;
        }


        try {
            //判断card的type是否万能卡

            //根据金额找相应第三方卡

            //找出全部万能卡，根据面额计算有多少张

            Long cardId = Long.parseLong(bizRequest.getCard_id());

            TCard card = cardService.findByCardId(cardId);
            if (card == null) {
                bizResp.setResult_code(BusiError.ERR_CODE_CARD_NOT_EXIST);
                bizResp.setError_message(BusiError.ERR_MSG_CARD_NOT_EXIST);
                return bizResp;
            }

            if (!card.getType().equalsIgnoreCase(TCard.TYPE_MASTER)) {
                bizResp.setResult_code(BusiError.ERR_CODE_CARD_TYPE_ERROR);
                bizResp.setError_message(BusiError.ERR_MSG_CARD_TYPE_ERROR);
                return bizResp;
            }

            logger.info("bizRequest.getPage() = " + bizRequest.getPage());

            List<TCard> otherCardList = new ArrayList<>();
            if (1 == bizRequest.getPage()){
                otherCardList = cardService.findByEnableAndChangepagestatusAndFeeOrderByOrdernumAsc(true, TCard.STATUS_SHOW, card.getFee());
            }
            //List<TCard> masterCardList = cardService.findByEnableAndStatusAndTypeOrderByOrdernumAsc(true, TCard.STATUS_SHOW, card.getType());

            List<CardChangeItem> cardChangeList = new ArrayList<>();
            for (TCard otherCard : otherCardList) {
                if (!otherCard.getType().equalsIgnoreCase(TCard.TYPE_MASTER)) {
                    CardChangeItem cardChangeItem = new CardChangeItem();
                    cardChangeItem.setCard_id(String.valueOf(otherCard.getCardId()));
                    cardChangeItem.setType(otherCard.getType());
                    cardChangeItem.setCard_name(otherCard.getCardName());
                    cardChangeItem.setPicture_url(imageUploadUrl + otherCard.getPictureUlr());
                    cardChangeItem.setGainBackgroundUrl(imageUploadUrl + otherCard.getGainBackgroundUrl());
                    cardChangeItem.setDetailBackgroundUrl(imageUploadUrl + otherCard.getDetailBackgroundUrl());
                    if (otherCard.getEffectiveDay() % 30 == 0 && otherCard.getEffectiveDay() >= 30) {
                        cardChangeItem.setEffectiveDay((int) (otherCard.getEffectiveDay() / 30) + "个月");
                    } else {
                        cardChangeItem.setEffectiveDay(otherCard.getEffectiveDay() + "天");
                    }

                    String effectiveTimeString = "";
                    if (otherCard.getEffectiveDay() != null) {
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                        effectiveTimeString = dateFormat.format(TimeUtil.addDateNDay(new Date(), otherCard.getEffectiveDay()));
                        effectiveTimeString = "有效期至" + effectiveTimeString;
                    }
                    cardChangeItem.setEffectiveTime(effectiveTimeString);
                    cardChangeItem.setFee(String.valueOf(card.getFee()));
                    cardChangeItem.setDetail(otherCard.getDetail());
                    cardChangeItem.setNumber("1");
                    cardChangeList.add(cardChangeItem);
                }
            }

//            for (TCard masterCard : masterCardList) {
//                if (masterCard.getCardId().longValue() != card.getCardId()) {
//                    int multipleNumber = card.getFee() / masterCard.getFee();
//                    int remain = card.getFee() % masterCard.getFee();
//                    if (remain == 0 && multipleNumber >= 1) {
//                        CardChangeItem cardChangeItem = new CardChangeItem();
//                        cardChangeItem.setCard_id(String.valueOf(masterCard.getCardId()));
//                        cardChangeItem.setType(masterCard.getType());
//                        cardChangeItem.setCard_name(masterCard.getCardName());
//                        cardChangeItem.setPicture_url(imageUploadUrl + masterCard.getPictureUlr());
//                        cardChangeItem.setGainBackgroundUrl(imageUploadUrl + masterCard.getGainBackgroundUrl());
//                        cardChangeItem.setDetailBackgroundUrl(imageUploadUrl + masterCard.getDetailBackgroundUrl());
//                        if (masterCard.getEffectiveDay() % 30 == 0 && masterCard.getEffectiveDay() >= 30) {
//                            cardChangeItem.setEffectiveDay((int) (masterCard.getEffectiveDay() / 30) + "个月");
//                        } else {
//                            cardChangeItem.setEffectiveDay(masterCard.getEffectiveDay() + "天");
//                        }
//
//                        String effectiveTimeString = "";
//                        if (masterCard.getEffectiveDay() != null) {
//                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
//                            effectiveTimeString = dateFormat.format(TimeUtil.addDateNDay(new Date(), masterCard.getEffectiveDay()));
//                            effectiveTimeString = "有效期至" + effectiveTimeString;
//                        }
//                        cardChangeItem.setEffectiveTime(effectiveTimeString);
//                        cardChangeItem.setFee(String.valueOf(card.getFee()));
//                        cardChangeItem.setDetail(masterCard.getDetail());
//                        cardChangeItem.setNumber(String.valueOf(multipleNumber));
//                        cardChangeList.add(cardChangeItem);
//                    }
//                }
//            }



            bizResp.setDataList(cardChangeList);
            bizResp.setResult_code(BusiError.ERR_CODE_SUCCESS);
            bizResp.setError_message("");
            return bizResp;
        } catch (Exception e) {
            bizResp.setResult_code(BusiError.ERR_CODE_DB_SAVE);
            bizResp.setError_message(BusiError.ERR_MSG_DB_SAVE);
            return bizResp;
        }


    }

    @Override
    public ValidateRet checkParam(CardChangeListQueryReq req, CardChangeListQueryResp resp) {
        ValidateRet vRet = super.checkParam(req, resp);
        if (!vRet.isValid())
            return vRet;
        List<ValidateParam> paramList = new ArrayList<ValidateParam>();
        paramList.add(new ValidateParam("card_id", ValidateType.NOTBLANK, req.getCard_id()));

        vRet = ValidateUtil.validate(paramList);
        if (vRet == null) {
            vRet = new ValidateRet(true, "");
        }
        if (!vRet.isValid()) {
            resp.setResult_code(BusiError.ERR_CODE_PARAM_BAD_REQ);
            resp.setError_message(vRet.getErrMsg());
        }

        return vRet;
    }
}
